﻿#region Copyright (c) 2013-03, Olaf Kober <amarok.projects@gmail.com>
//================================================================================
//	Permission is hereby granted, free of charge, to any person obtaining a copy
//	of this software and associated documentation files (the "Software"), to deal
//	in the Software without restriction, including without limitation the rights
//	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//	copies of the Software, and to permit persons to whom the Software is
//	furnished to do so, subject to the following conditions:
//
//	The above copyright notice and this permission notice shall be included in
//	all copies or substantial portions of the Software.
//
//	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//	THE SOFTWARE.
//================================================================================
#endregion

#if TESTS

using System;
using System.Threading;
using System.Threading.Tasks;
using Amarok.Agents.Resources;
using NUnit.Framework;


namespace Amarok.Agents
{
	[TestFixture]
	public class Test_Subsystem
	{
		private class DummySubsystemFactory : ISubsystemFactory
		{
			public ISubsystem LoadSubsystem(Type subsystemType, RuntimeEnvironment environment)
			{
				throw new NotImplementedException();
			}
		}

		private class StubEnvironment : RuntimeEnvironment
		{
			public StubEnvironment(IRuntime runtime, IMessageBus messageBus)
				: base(runtime, messageBus)
			{
			}
		}

		private class MockMessageBus : IMessageBus
		{
			public Int32 ConnectCalled;

			public ICompletable Connect(IAgent agent)
			{
				ConnectCalled++;
				return new DummyCompletable();
			}

			public ICompletable Connect(Object label, IAgent agent)
			{
				throw new NotImplementedException();
			}

			public void Publish(Message message)
			{
				throw new NotImplementedException();
			}

			public void Publish(Object label, Message message)
			{
				throw new NotImplementedException();
			}

			public Task<TResult> PublishOperation<TResult, TProgress>(Operation<TResult, TProgress> operation, Action<TProgress> progressAction = null)
			{
				throw new NotImplementedException();
			}

			public Task<TResult> PublishOperation<TResult, TProgress>(object label, Operation<TResult, TProgress> operation, Action<TProgress> progressAction = null)
			{
				throw new NotImplementedException();
			}

			public ICompletable Subscribe(Type messageType, AgentReference subscriber, Predicate<Message> messageFilter = null)
			{
				throw new NotImplementedException();
			}

			public ICompletable Subscribe(Type messageType, Action<Message> callback, Predicate<Message> messageFilter = null)
			{
				throw new NotImplementedException();
			}

			public void Dispose()
			{
				throw new NotImplementedException();
			}

			public Task Completion
			{
				get
				{
					throw new NotImplementedException();
				}
			}

			public void Complete(Boolean discardAvailableMessages = false)
			{
				throw new NotImplementedException();
			}
		}

		private class MockSubsystem : Subsystem
		{
			public Int32 OnLoadCalled;
			public Int32 OnCompleteCalled;
			public Boolean ThrowInOnCleanup;
			public Boolean ThrowExceptionInOnLoad;
			public Boolean ThrowSubsystemLoadExceptionInOnLoad;
			public AutoResetEvent OnCleanupSignal = new AutoResetEvent(false);

			public MockSubsystem(RuntimeEnvironment environment)
				: base(environment)
			{
			}

			public new StubEnvironment Environment
			{
				get
				{
					return (StubEnvironment)base.Environment;
				}
			}

			protected override void OnLoad()
			{
				OnLoadCalled++;

				base.SpawnAgent(typeof(MockAgent));
				base.SpawnAgent(typeof(MockAgent), AgentOptions.Empty);
				base.SpawnAgent(typeof(MockAgent), base.Environment, AgentOptions.Empty);
				base.SpawnAgent<MockAgent>();
				base.SpawnAgent<MockAgent>(AgentOptions.Empty);
				base.SpawnAgent<MockAgent>(base.Environment, AgentOptions.Empty);
				base.SpawnAgent<MockAgent, StubEnvironment, AgentOptions>(this.Environment, AgentOptions.Empty);

				base.LoadSubsystem(typeof(MockSubsystem2));
				base.LoadSubsystem(typeof(MockSubsystem2), base.Environment);
				base.LoadSubsystem<MockSubsystem2>();
				base.LoadSubsystem<MockSubsystem2>(base.Environment);
				base.LoadSubsystem<MockSubsystem2, StubEnvironment>(this.Environment);

				base.OnLoad();

				if (ThrowExceptionInOnLoad)
					throw new Exception("ONLOAD");
				if (ThrowSubsystemLoadExceptionInOnLoad)
					throw new SubsystemLoadException("ONLOAD");
			}

			protected override Task OnComplete(Boolean discardAvailableMessages)
			{
				OnCompleteCalled++;

				return base.OnComplete(discardAvailableMessages);
			}

			protected override void OnCleanup()
			{
				base.OnCleanup();

				OnCleanupSignal.Set();

				if (ThrowInOnCleanup)
					throw new ApplicationException("ONCLEANUP");
			}
		}

		private class MockSubsystem2 : Subsystem
		{
			public static Int32 OnLoadCalled;
			public static Int32 OnCompleteCalled;

			public MockSubsystem2(RuntimeEnvironment environment)
				: base(environment)
			{
			}

			protected override void OnLoad()
			{
				base.OnLoad();

				OnLoadCalled++;
			}

			protected override Task OnComplete(Boolean discardAvailableMessages)
			{
				OnCompleteCalled++;

				return base.OnComplete(discardAvailableMessages);
			}
		}

		[MessageBusConnected]
		private class MockAgent : Agent<StubEnvironment, AgentOptions>
		{
			public static Int32 OnCompleteCalled;

			public MockAgent(StubEnvironment environment, AgentOptions options)
				: base(environment, options)
			{
			}

			protected override Task OnComplete(Boolean discardAvailableMessages)
			{
				OnCompleteCalled++;

				return base.OnComplete(discardAvailableMessages);
			}
		}


		[SetUp]
		public void TestSetup()
		{
			MockAgent.OnCompleteCalled = 0;
			MockSubsystem2.OnLoadCalled = 0;
			MockSubsystem2.OnCompleteCalled = 0;
		}


		// --- TESTS ---


		#region Factory

		[Test]
		public void Test_Factory()
		{
			var factory1 = Subsystem.Factory;
			var factory2 = Subsystem.Factory;

			Assert.That(factory1, Is.TypeOf<DefaultSubsystemFactory>());
			Assert.That(factory2, Is.SameAs(factory1));
		}

		[Test]
		public void Test_SetFactory()
		{
			Assert.That(Subsystem.Factory, Is.TypeOf<DefaultSubsystemFactory>());

			var factory = new DummySubsystemFactory();
			Subsystem.SetFactory(factory);

			Assert.That(Subsystem.Factory, Is.SameAs(factory));

			Subsystem.SetFactory(new DefaultSubsystemFactory());

			Assert.That(Subsystem.Factory, Is.TypeOf<DefaultSubsystemFactory>());
		}

		[Test]
		public void Test_SetFactory_Null()
		{
			Assert.That(Subsystem.Factory, Is.TypeOf<DefaultSubsystemFactory>());

			Assert.Throws<ArgumentNullException>(() =>
				{
					Subsystem.SetFactory(null);
				});

			Assert.That(Subsystem.Factory, Is.TypeOf<DefaultSubsystemFactory>());
		}

		#endregion

		#region Construction

		[Test]
		public void Test_Construction()
		{
			var runtime = new DummyRuntime();
			var messageBus = new MockMessageBus();
			var environment = new StubEnvironment(runtime, messageBus);

			var subsystem = new MockSubsystem(environment);

			Assert.That(subsystem.OnLoadCalled, Is.EqualTo(0));
			Assert.That(subsystem.OnCompleteCalled, Is.EqualTo(0));
			Assert.That(subsystem.Environment, Is.SameAs(environment));
			Assert.That(messageBus.ConnectCalled, Is.EqualTo(0));
		}

		[Test]
		public void Test_Construction_NullEnvironment()
		{
			Assert.Throws<ArgumentNullException>(() =>
				{
					var subsystem = new MockSubsystem(null);
				});
		}

		#endregion

		#region Load

		[Test]
		public void Test_Load_Complete_ProcessAvailableMessages()
		{
			var runtime = new DummyRuntime();
			var messageBus = new MockMessageBus();
			var environment = new StubEnvironment(runtime, messageBus);

			var subsystem = new MockSubsystem(environment);

			Assert.That(subsystem.OnLoadCalled, Is.EqualTo(0));
			Assert.That(subsystem.OnCompleteCalled, Is.EqualTo(0));
			Assert.That(subsystem.Environment, Is.SameAs(environment));
			Assert.That(MockAgent.OnCompleteCalled, Is.EqualTo(0));
			Assert.That(MockSubsystem2.OnLoadCalled, Is.EqualTo(0));
			Assert.That(MockSubsystem2.OnCompleteCalled, Is.EqualTo(0));
			Assert.That(messageBus.ConnectCalled, Is.EqualTo(0));

			((ISubsystem)subsystem).Load();

			Assert.That(subsystem.OnLoadCalled, Is.EqualTo(1));
			Assert.That(subsystem.OnCompleteCalled, Is.EqualTo(0));
			Assert.That(subsystem.Environment, Is.SameAs(environment));
			Assert.That(MockAgent.OnCompleteCalled, Is.EqualTo(0));
			Assert.That(MockSubsystem2.OnLoadCalled, Is.EqualTo(5));
			Assert.That(MockSubsystem2.OnCompleteCalled, Is.EqualTo(0));
			Assert.That(messageBus.ConnectCalled, Is.EqualTo(7));

			((ISubsystem)subsystem).Complete(false);
			((ISubsystem)subsystem).Completion.Wait();

			Assert.That(subsystem.OnLoadCalled, Is.EqualTo(1));
			Assert.That(subsystem.OnCompleteCalled, Is.EqualTo(1));
			Assert.That(subsystem.Environment, Is.SameAs(environment));
			Assert.That(MockAgent.OnCompleteCalled, Is.EqualTo(7));
			Assert.That(MockSubsystem2.OnLoadCalled, Is.EqualTo(5));
			Assert.That(MockSubsystem2.OnCompleteCalled, Is.EqualTo(5));
			Assert.That(messageBus.ConnectCalled, Is.EqualTo(7));
		}

		[Test]
		public void Test_Load_Dispose()
		{
			var runtime = new DummyRuntime();
			var messageBus = new MockMessageBus();
			var environment = new StubEnvironment(runtime, messageBus);

			var subsystem = new MockSubsystem(environment);

			Assert.That(subsystem.OnLoadCalled, Is.EqualTo(0));
			Assert.That(subsystem.OnCompleteCalled, Is.EqualTo(0));
			Assert.That(subsystem.Environment, Is.SameAs(environment));
			Assert.That(MockAgent.OnCompleteCalled, Is.EqualTo(0));
			Assert.That(MockSubsystem2.OnLoadCalled, Is.EqualTo(0));
			Assert.That(MockSubsystem2.OnCompleteCalled, Is.EqualTo(0));
			Assert.That(messageBus.ConnectCalled, Is.EqualTo(0));

			((ISubsystem)subsystem).Load();

			Assert.That(subsystem.OnLoadCalled, Is.EqualTo(1));
			Assert.That(subsystem.OnCompleteCalled, Is.EqualTo(0));
			Assert.That(subsystem.Environment, Is.SameAs(environment));
			Assert.That(MockAgent.OnCompleteCalled, Is.EqualTo(0));
			Assert.That(MockSubsystem2.OnLoadCalled, Is.EqualTo(5));
			Assert.That(MockSubsystem2.OnCompleteCalled, Is.EqualTo(0));
			Assert.That(messageBus.ConnectCalled, Is.EqualTo(7));

			Helper.Dispose(subsystem);

			Assert.That(subsystem.OnLoadCalled, Is.EqualTo(1));
			Assert.That(subsystem.OnCompleteCalled, Is.EqualTo(1));
			Assert.That(subsystem.Environment, Is.SameAs(environment));
			Assert.That(MockAgent.OnCompleteCalled, Is.EqualTo(7));
			Assert.That(MockSubsystem2.OnLoadCalled, Is.EqualTo(5));
			Assert.That(MockSubsystem2.OnCompleteCalled, Is.EqualTo(5));
			Assert.That(messageBus.ConnectCalled, Is.EqualTo(7));
		}

		[Test]
		public void Test_Load_Complete_Exception_In_OnCleanup()
		{
			var runtime = new DummyRuntime();
			var messageBus = new MockMessageBus();
			var environment = new StubEnvironment(runtime, messageBus);

			var subsystem = new MockSubsystem(environment);
			subsystem.ThrowInOnCleanup = true;

			Assert.That(subsystem.OnLoadCalled, Is.EqualTo(0));
			Assert.That(subsystem.OnCompleteCalled, Is.EqualTo(0));
			Assert.That(subsystem.Environment, Is.SameAs(environment));
			Assert.That(MockAgent.OnCompleteCalled, Is.EqualTo(0));
			Assert.That(MockSubsystem2.OnLoadCalled, Is.EqualTo(0));
			Assert.That(MockSubsystem2.OnCompleteCalled, Is.EqualTo(0));

			((ISubsystem)subsystem).Load();

			Assert.That(subsystem.OnLoadCalled, Is.EqualTo(1));
			Assert.That(subsystem.OnCompleteCalled, Is.EqualTo(0));
			Assert.That(subsystem.Environment, Is.SameAs(environment));
			Assert.That(MockAgent.OnCompleteCalled, Is.EqualTo(0));
			Assert.That(MockSubsystem2.OnLoadCalled, Is.EqualTo(5));
			Assert.That(MockSubsystem2.OnCompleteCalled, Is.EqualTo(0));

			((ISubsystem)subsystem).Complete(false);
			((ISubsystem)subsystem).Completion.Wait();

			Assert.That(subsystem.OnCleanupSignal.WaitOne(5000), Is.True);

			Assert.That(subsystem.OnLoadCalled, Is.EqualTo(1));
			Assert.That(subsystem.OnCompleteCalled, Is.EqualTo(1));
			Assert.That(subsystem.Environment, Is.SameAs(environment));
			Assert.That(MockAgent.OnCompleteCalled, Is.EqualTo(7));
			Assert.That(MockSubsystem2.OnLoadCalled, Is.EqualTo(5));
			Assert.That(MockSubsystem2.OnCompleteCalled, Is.EqualTo(5));
		}

		[Test]
		public void Test_Load_Exception_In_Load()
		{
			var runtime = new DummyRuntime();
			var messageBus = new MockMessageBus();
			var environment = new StubEnvironment(runtime, messageBus);

			var subsystem = new MockSubsystem(environment);
			subsystem.ThrowExceptionInOnLoad = true;

			var exception = Assert.Throws<SubsystemLoadException>(() =>
				{
					((ISubsystem)subsystem).Load();
				});

			Assert.That(exception.Message, Is.EqualTo(SubsystemResources.SubsystemLoadFailure));
			Assert.That(exception.GetBaseException().Message, Is.EqualTo("ONLOAD"));
		}

		[Test]
		public void Test_Load_SubsystemLoadException_In_Load()
		{
			var runtime = new DummyRuntime();
			var messageBus = new MockMessageBus();
			var environment = new StubEnvironment(runtime, messageBus);

			var subsystem = new MockSubsystem(environment);
			subsystem.ThrowSubsystemLoadExceptionInOnLoad = true;

			var exception = Assert.Throws<SubsystemLoadException>(() =>
				{
					((ISubsystem)subsystem).Load();
				});

			Assert.That(exception.Message, Is.EqualTo("ONLOAD"));
			Assert.That(exception.InnerException, Is.Null);
		}

		#endregion

	}
}

#endif
